<?php
/*
 * @灯商云端
 * @功能说明：用户中心
 * @更新说明：暂无更新
 * @文件名 UserOldController.class.php
 * @编码 UTF-8
 * @创建时间 2015-7-21 下午3:38:52
 * @创建人 XING
 */

namespace home\Controller;

use dg\Model\ResEntityModel;

use Think\Controller;

class UserController extends ApibaseController
{
    function __construct() {
        parent::__construct();
    }

    /*
     * 登陆模块
     * @date: 2015-3-21下午2:10:37
     * @editor: XING
     */
    public function login() {
        global $isLogin;
        if ($isLogin){
            redirect('/user/admin?res=0-1');
        }else{
            $this->display('user/login');
        }
    }

    /*
     * 系统用户注册
     * @date: 2015-3-21下午2:20:22
     * @editor: XING
     */
    public function regist() {
    	throw new \Exception('非法请求');exit;
        //注册页面渲染
        $this->display('user/regist');
    }

    /*
     * 系统登陆
     * @date: 2015-3-21下午2:48:06
     * @editor: XING
     */
    public function checklogin() {
        $userMsg = M('trb_hospital',null)->where(array('main_code' => I('post.username')))->find();

        if ($userMsg['password'] == md5(I('post.passwd') . $userMsg['salt'])) {

            $pushSession = array('name' => I('post.username'));
            if (I('post.signlogin') == 1) {
                $setSecret = md5(I('post.username') . 'ajwUid' . time());
                M('trb_hospital',null)->where(array('main_code' => I('post.username')))->setField(
                    array('remember_token' => $setSecret)
                );

                cookie('_ajwunion', $setSecret, 'expire=604800');
                $pushSession['expire'] = 604800;
            }
            $role_id = M('AuthGroupAccess')->where(['uid'=>$userMsg['id']])->getField('role_id');
            session($pushSession);
            session('role_id',$role_id);
            session('loginUid', $userMsg['id']);

            cookie('ajwUid', base64_encode(I('post.username')) . randstr(), 'expire=604800');

            session(I('post.username'), true);
//            echo base64_decode(substr(cookie('ajwUid'),0,-1));exit;
            //putlog('登陆系统', 'UserController', 'checklogin');
            jsonRespons('1', '登陆成功！');
        } else {

            jsonRespons('0', '帐号或密码有误！');
        }
    }



    /*
     * 系统注销操作
     * @date: 2015-3-23下午12:02:30
     * @editor: XING
     */
    public function loginout() {
        session('role_id',null);
        session('loginUid',null);
        session(cookie('PHPSESSID'), null);
        session(getLoginMsg()->username, null);
        session('role_id',null);
        cookie('ajwUid', null);
        cookie('_ajwunion', null);
        cookie('PHPSESSID', null);
        redirect('/index/index');
    }

    /*
     * 个人中心简介
     * @date: 2015-3-23下午2:30:20
     * @editor: XING
     */
    public function usercenter() {

        //个人页面渲染
        $this->display('user/usercenter');
    }
    /*
       * 个人中心资料编辑
       * @date: 2015-3-23下午5:06:13
       * @editor: XING
       */
    public function userUpdate() {
        if (I('post.update')) {
            $data = array('email' => I('post.email'));
            if (I('post.password')) {
                $salt = randstr(5);
                $data['password'] = md5(I('post.password') . $salt);
                $data['salt'] = $salt;
            }
            $data['email'] = I('post.email');
            session('kfLine' . I('post.rid'), I('post.lineStatus') == '1' ? '1' : null);
            $keArr = session('kfLineArr');
            if (I('post.lineStatus') == '1') {
                if (isset($keArr[I('post.rid')]) && $keArr[I('post.rid')] = I('post.rid')) {
                    // Nothing to do
                } else {
                    $keArr[I('post.rid')] = I('post.rid');
                }
                session('kfLineArr', $keArr);
            } else {
                if (isset($keArr[I('post.rid')])) {
                    unset($keArr[I('post.rid')]);
                    session('kfLineArr', $keArr);
                }
            }
            M('trb_hospital',null)->where(array('rid' => session('loginUid')))->setField($data);

            $this->showtips('信息编辑成功');
        }
    }

    /*
     * 后台管理员管理
     * @date: 2016-9-21 上午15:41:13
     * @editor: liuqi
     */
    public function admin(){
        if(!is_login()){
            redirect('/user/login');exit;
        }
        $page = I('get.page') ?: 1;
        $perpage = 10;
        $url = '';
        $admin = M('ResEntity e')
            ->field('e.rid,e.username,e.realname,e.mobile,e.is_active,r.name role_name,e.email,e.add_at')
            ->join('hos_auth_group_access a on a.uid=e.rid')
            ->join('hos_role r on r.id=a.role_id')
            ->page($page, $perpage)
            ->select();
        $this->assign('getData',$admin);
        $this->assign('page', setPage(M('ResEntity')->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('user/account_management');
    }

    /**
     * 用户禁用启用(status 1禁用 2启用)
     */
    public function user_status(){
        if(I('post.rid') && I('post.status')){
            $user_id = I('post.rid');
            $status = I('post.status')==1 ? 1:0;
            $rs = M('ResEntity')->where(['rid'=>$user_id])->setField(['is_active'=>$status]);
            if ($rs){
                dataFormat('',0,'success');
            }
        }else {
            dataFormat('',1,'参数缺失');
        }
    }

    /**
     * 添加后台管理员
    */
    public function addAdmin(){
        if (I('post.postData')) {
            parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
        }
        if($postData['realname'] && $postData['mobile'] && $postData['password'] && $postData['role_id']){
            $admin_mobile = M('ResEntity')->where(['mobile'=>$postData['mobile']])->find();
            if ($admin_mobile){
                dataFormat('',1,'该手机号用户已存在');
            }
            $salts = randstr(5);
            $data = [
                'realname'          => $postData['realname'],
                'password'          => md5($postData['password'].$salts),
                'salt'              => $salts,
                'mobile'            => $postData['mobile'],
                'email'             => $postData['email'],
                'role_id'           => $postData['role_id'],
                'remember_token'    => '',
                'add_at'            => time(),
                'update_at'         => time()
            ];
            $res = M('ResEntity')->add($data);
            if($postData['role_id']){
                M('AuthGroupAccess')->add(['uid'=>$res,'role_id'=>$postData['role_id']]);
            }
//            putlog('添加管理员'.$postData['user_name'],'UserController','addAdmin');
            if($res){
                dataFormat('',0,'添加管理员成功');
            }else{
                dataFormat('',1,'添加失败');
            }
        }else{
            dataFormat('',1,'参数缺失');
        }
    }
    /*
     * 后台管理员管理
     * @date: 2016-9-21 上午15:51:26
     * @editor: liuqi
     */
    public function addAdmin2(){
        if(!is_login()){
            redirect('/user/login');exit;
        }
        /*用户注册逻辑*/
        if(I('post.submit')){
            if(I('post.rid')){
                $data = array('email'=>I('post.email'));
                if(I('post.password')){
                    $salt = randstr(5);
                    $data['password'] = md5(I('post.password').$salt);
                    $data['salt'] = $salt;
                }
                $data['username'] = I('post.username');
                if(I('post.role_id')){
                    M('AuthGroupAccess')->where(['uid'=>I('post.rid')])->setField(['role_id'=>I('post.role_id')]);
                    $data['role_id'] = I('post.role_id');
                }
                M('ResEntity')->where(['rid'=>I('post.rid')])->setField($data);
                putlog('修改管理员'.$data['username'].'的信息','UserController','addAdmin');
                $this->showtips('信息编辑成功');
            }
            $salts = randstr(5);
            $data = [
                'username'          => I('post.username'),
                'password'          => md5(I('post.password').$salts),
                'salt'              => $salts,
                'email'             => I('post.email'),
                'role_id'           => I('post.role_id'),
                'remember_token'    => '',
                'add_at'            => time(),
                'update_at'         => time()
            ];
            $res = M('ResEntity')->add($data);
            if(I('post.role_id')){
                M('AuthGroupAccess')->add(['uid'=>$res,'role_id'=>I('post.role_id')]);
            }
            putlog('添加管理员'.I('post.username'),'UserController','addAdmin');
            if($res){
                $this->showtips('添加管理员成功');
            }else{
                $this->showtips('操作失败');
            }
        }
        $admin_info = M('ResEntity e')
            ->join('hos_auth_group_access a on a.uid=e.id')
            ->join('hos_role r on r.id=a.role_id')
            ->where(['e.id'=>I('get.rid')])
            ->find();
        $this->assign('admin_info',$admin_info);
        $role = M('role')->where(['status'=>1])->select();
        $this->assign('role',$role);
        //注册页面渲染
        $this->display('user/addadmin');
    }

    /**
     * 返回管理员角色
     */
    public function adminRole(){
        $role = M('Role')->where(['status'=>1])->select();
        if($role){
            dataFormat($role,'0','success');
        }
    }

    /**
     * 科室管理
     */
    public function department_management(){
        $this->display('user/department_management');
    }

    public function patient_management(){
        $this->display('user/patient_management');
    }


    public function patient_call_management(){
        $this->display('user/patient_call_management');
    }
    public function hospital_call_management(){
        $this->display('user/hospital_call_management');
    }
    public function warning_deal_management(){
        $this->display('user/warning_deal_management');
    }
    public function warning_record_management(){
        $this->display('user/warning_record_management');
    }
    public function warning_bind_management(){
        $this->display('user/warning_bind_management');
    }
    public function patient_all_complain_management(){
        $this->display('user/patient_all_complain_management');
    }
    public function logistics_management(){
        $this->display('user/logistics_management');
    }
    public function notice_management(){
        $this->display('user/notice_management');
    }
    public function account_management(){
        $this->display('user/account_management');
    }

    /**
     * ZP券防伪码生成（券号顺序19201，到24700 1.24再加500张到25200）
    */
//    public function make_code(){
//        for($i=24701; $i<=25200; $i++){
//            M('Fangweima')->add([
//                'bianhao' => 'ZP00'.$i,
//                'fangweima' => $this->getRandomString(9),
//                'new_id' => $i.'002',
//            ]);
//        }
//    }

    function getRandomString($len, $chars=null)
    {
        if (is_null($chars)) {
            $chars = "ABCDEFGHJKMNPQRSTUVWXYZ123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
}